import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.io.FileUtils;

public class ConvertCharset {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		File src = args.length >= 1 ? new File(args[0]) : new File(readLine(
				"输入源文件：", in));
		File dest = args.length >= 2 ? new File(args[1]) : new File(readLine(
				"输入目标文件：", in));
		String suffix = args.length >= 3 ? args[2] : readLine("需要转换的文件后缀（空所有）：",
				in).trim();
		String srcCharset = args.length >= 4 ? args[3]
				: readLine("源文件字符集：", in);
		String destCharset = args.length >= 5 ? args[4] : readLine("目标文件字符集：",
				in);

		convert(src, dest, srcCharset, destCharset, suffix);
		in.close();
	}

	private static String readLine(String msg, BufferedReader in)
			throws IOException {
		System.out.print(msg);
		return in.readLine();
	}

	private static void convert(File src, File dest, String srcCharset,
			String destCharset, String suffix) throws IOException {
		if (src.exists() == false) {
			System.err.println("源文件不存在：" + src);
			return;
		}
		// 处理目录
		if (src.isDirectory()) {
			if (!dest.exists() && !dest.mkdir()) {
				System.err.println("创建目录失败：" + dest);
				return;
			}
			File[] list = src.listFiles();
			if (list != null && list.length > 0) {
				for (File file : list) {
					convert(file, new File(dest, file.getName()), srcCharset,
							destCharset, suffix);
				}
			}
			return;
		}
		// 转换文件编码字符集
		if (src.isFile()
				&& ("".equals(suffix) || src.getName().endsWith(suffix))) {
			if (!dest.exists() && !dest.createNewFile()) {
				System.err.println("无法创建文件：" + dest);
				return;
			}
			String data = FileUtils.readFileToString(src, srcCharset);
			FileUtils.writeStringToFile(dest, data, destCharset);
			return;
		}
		System.err.println("跳过转换：" + src + "  =>  " + dest);
	}
}
